package com.grapes.widget;

import com.grapes.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

public class GrapesTabBar extends LinearLayout {

	private Button leftBtn;
	private Button rightBtn;
	private TabBarSelectedSwitchLister switchListener;

	public GrapesTabBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.GrapesTabBar);
		int selectedIndex = typedArray.getInteger(
				R.styleable.GrapesTabBar_selectedIndex, 0);
		leftBtn = new Button(context);		
		leftBtn.setOnClickListener(clickListener);
		leftBtn.setText(R.string.has_deadline);
		rightBtn = new Button(context);
		rightBtn.setOnClickListener(clickListener);
		rightBtn.setText(R.string.no_deadline);
		if (selectedIndex == 0) {
			leftBtn.setBackgroundResource(R.color.dark_gray);
			rightBtn.setBackgroundResource(R.color.lighter_gray);
		} else {
			leftBtn.setBackgroundResource(R.color.lighter_gray);
			rightBtn.setBackgroundResource(R.color.dark_gray);
		}
		LinearLayout.LayoutParams leftBtnLayoutParam = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		leftBtnLayoutParam.weight=1;
		addView(leftBtn,leftBtnLayoutParam);
		
		LinearLayout.LayoutParams rightBtnLayoutParam = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		rightBtnLayoutParam.weight=1;
		addView(rightBtn,rightBtnLayoutParam);
	}

	public void setTabBarSelectedSwitchLister(
			TabBarSelectedSwitchLister listener) {
		switchListener = listener;
	}

	View.OnClickListener clickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Button btn = (Button) v;
			if (btn.equals(leftBtn)) {
				leftBtn.setBackgroundResource(R.color.dark_gray);
				rightBtn.setBackgroundResource(R.color.lighter_gray);
				if (switchListener != null)
					switchListener.onSelectedSwitch(1, 0);
			} else {
				leftBtn.setBackgroundResource(R.color.lighter_gray);
				rightBtn.setBackgroundResource(R.color.dark_gray);
				if (switchListener != null)
					switchListener.onSelectedSwitch(0, 1);
			}
		}
	};

	public GrapesTabBar(Context context) {
		super(context);
	}

	public interface TabBarSelectedSwitchLister {
		public void onSelectedSwitch(int previousIndex, int currentIndex);
	}

}
